﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AyuBookmark.Common.Interfaces;
using AyuBookmark.Common.Models;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace AyuBookmark.Service.Services
{
    /// <summary>
    /// 浏览器活动监控服务
    /// </summary>
    public class MonitorService : IHostedService, IDisposable
    {
        private readonly IBookmarkService _bookmarkService;
        private readonly IConfigRepository _configRepository;
        private readonly ILogger<MonitorService> _logger;
        private Timer _timer;
        private bool _isMonitoring;
        private DateTime _lastCheckTime = DateTime.MinValue;

        // 浏览器进程名称列表
        private static readonly string[] BrowserProcessNames =
        {
            "chrome", "firefox", "msedge", "iexplore", "opera"
        };

        /// <summary>
        /// 初始化监控服务
        /// </summary>
        public MonitorService(
            IBookmarkService bookmarkService,
            IConfigRepository configRepository,
            ILogger<MonitorService> logger)
        {
            _bookmarkService = bookmarkService ?? throw new ArgumentNullException(nameof(bookmarkService));
            _configRepository = configRepository ?? throw new ArgumentNullException(nameof(configRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        #region 监控控制
        /// <summary>
        /// 启动监控服务
        /// </summary>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Monitor Service starting...");

            // 从配置获取监控间隔（默认30秒）
            var interval = _configRepository.GetConfigValueAsync("MonitoringInterval", 30).GetAwaiter().GetResult();

            _timer = new Timer(DoMonitoringWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(interval));

            _isMonitoring = true;
            return Task.CompletedTask;
        }

        /// <summary>
        /// 停止监控服务
        /// </summary>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Monitor Service stopping...");

            _timer?.Change(Timeout.Infinite, 0);
            _isMonitoring = false;
            return Task.CompletedTask;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _timer?.Dispose();
        }
        #endregion

        #region 监控逻辑
        private async void DoMonitoringWork(object state)
        {
            if (!_isMonitoring) return;

            try
            {
                // 获取活动浏览器窗口
                var activeUrls = GetActiveBrowserUrls();

                // 获取配置的停留时间阈值（秒）
                var stayDuration = await _configRepository.GetConfigValueAsync("StayDuration", 30);

                // 处理每个活动的URL
                foreach (var urlInfo in activeUrls)
                {
                    // 检查停留时间是否超过阈值
                    if (urlInfo.ActiveTime.TotalSeconds >= stayDuration)
                    {
                        await ProcessValidUrl(urlInfo.Url);
                    }
                }

                _lastCheckTime = DateTime.Now;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred during monitoring");
            }
        }

        private List<UrlActivityInfo> GetActiveBrowserUrls()
        {
            var activeUrls = new List<UrlActivityInfo>();
            var now = DateTime.Now;

            // 获取所有浏览器进程
            foreach (var processName in BrowserProcessNames)
            {
                try
                {
                    var processes = Process.GetProcessesByName(processName);
                    foreach (var process in processes)
                    {
                        // 获取窗口标题（通常包含当前页面标题和URL）
                        if (!string.IsNullOrEmpty(process.MainWindowTitle))
                        {
                            // 简单解析URL（实际项目中需要更复杂的解析逻辑）
                            var url = ExtractUrlFromWindowTitle(process.MainWindowTitle);
                            if (!string.IsNullOrEmpty(url))
                            {
                                // 计算活动时间（这里简化处理，实际应该跟踪每个URL的活动时间）
                                var activeTime = _lastCheckTime > DateTime.MinValue
                                    ? now - _lastCheckTime
                                    : TimeSpan.FromSeconds(1);

                                activeUrls.Add(new UrlActivityInfo(url, activeTime));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, $"Failed to monitor {processName} process");
                }
            }

            return activeUrls;
        }

        private async Task ProcessValidUrl(string url)
        {
            try
            {
                // 检查是否已存在该书签
                //var existingBookmark = await _bookmarkService.GetBookmarkDetailsAsync(url);
                var existingBookmark = await _bookmarkService.GetBookmarkByUrlAsync(url);
                if (existingBookmark == null)
                {
                    // 创建新书签
                    var newBookmark = new Bookmark
                    {
                        Url = url,
                        Title = GetTitleFromUrl(url),
                        CreatedTime = DateTime.Now
                    };

                    await _bookmarkService.AddBookmarkAsync(newBookmark);
                    _logger.LogInformation($"Added new bookmark: {url}");
                }
                else
                {
                    // 更新最后访问时间
                    existingBookmark.LastAccessed = DateTime.Now;
                    await _bookmarkService.UpdateBookmarkAsync(existingBookmark);
                    _logger.LogDebug($"Updated bookmark access time: {url}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Failed to process URL: {url}");
            }
        }
        #endregion

        #region 辅助方法
        private string ExtractUrlFromWindowTitle(string title)
        {
            // 简单实现：假设URL在标题末尾的括号中
            // 实际项目应该使用更可靠的方法，如Windows API
            var start = title.LastIndexOf('(');
            var end = title.LastIndexOf(')');

            if (start > 0 && end > start)
            {
                return title.Substring(start + 1, end - start - 1);
            }

            return null;
        }

        private string GetTitleFromUrl(string url)
        {
            // 简单实现：使用URL的主机名作为标题
            try
            {
                var uri = new Uri(url);
                return uri.Host.Replace("www.", "");
            }
            catch
            {
                return url;
            }
        }
        #endregion

        #region 辅助类
        private class UrlActivityInfo
        {
            public string Url { get; }
            public TimeSpan ActiveTime { get; }

            public UrlActivityInfo(string url, TimeSpan activeTime)
            {
                Url = url;
                ActiveTime = activeTime;
            }
        }
        #endregion
    }
}